package com.datagateway.component;

import com.datagateway.component.ConfigHotReloadManager.ConfigChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 配置变更事件监听器
 * 监听配置热更新事件并执行相应的处理逻辑
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@Component
public class ConfigChangeEventListener {

    private static final Logger logger = LoggerFactory.getLogger(ConfigChangeEventListener.class);

    @Autowired
    private DataBuffer dataBuffer;

    @Autowired
    private HiveWriter hiveWriter;

    @Autowired
    private GroovyScriptEngine groovyScriptEngine;

    @Autowired
    private AlertManager alertManager;

    @Autowired
    private SystemMonitor systemMonitor;

    /**
     * 监听配置变更事件
     * 
     * @param event 配置变更事件
     */
    @EventListener
    public void handleConfigChangeEvent(ConfigChangeEvent event) {
        try {
            logger.info("处理配置变更事件: {} = {} -> {}", 
                       event.getKey(), event.getOldValue(), event.getNewValue());
            
            // 根据配置键执行相应的处理逻辑
            String configKey = event.getKey();
            
            if (configKey.startsWith("kafka.")) {
                handleKafkaConfigChange(event);
            } else if (configKey.startsWith("hive.")) {
                handleHiveConfigChange(event);
            } else if (configKey.startsWith("groovy.")) {
                handleGroovyConfigChange(event);
            } else if (configKey.startsWith("alert.")) {
                handleAlertConfigChange(event);
            } else {
                handleGenericConfigChange(event);
            }
            
        } catch (Exception e) {
            logger.error("处理配置变更事件失败: {}", event.getKey(), e);
        }
    }

    /**
     * 处理Kafka配置变更
     * 
     * @param event 配置变更事件
     */
    private void handleKafkaConfigChange(ConfigChangeEvent event) {
        String configKey = event.getKey();
        
        switch (configKey) {
            case "kafka.consumer.max-poll-records":
                // 更新数据缓冲区的批处理大小
                try {
                    int maxPollRecords = Integer.parseInt(event.getNewValue().toString());
                    dataBuffer.updateBatchSize(maxPollRecords);
                    logger.info("已更新数据缓冲区批处理大小: {}", maxPollRecords);
                } catch (NumberFormatException e) {
                    logger.warn("无效的max-poll-records值: {}", event.getNewValue());
                }
                break;
                
            case "kafka.bootstrap-servers":
                // Kafka服务器地址变更需要重启消费者
                logger.warn("Kafka服务器地址已变更，需要重启应用: {}", event.getNewValue());
                alertManager.sendConfigChangeAlert("Kafka配置变更", 
                    "Kafka服务器地址已变更，需要重启应用: " + event.getNewValue());
                break;
                
            case "kafka.consumer.group-id":
                // 消费者组ID变更需要重启消费者
                logger.warn("Kafka消费者组ID已变更，需要重启应用: {}", event.getNewValue());
                alertManager.sendConfigChangeAlert("Kafka配置变更", 
                    "消费者组ID已变更，需要重启应用: " + event.getNewValue());
                break;
                
            default:
                logger.info("Kafka配置变更: {} = {}", configKey, event.getNewValue());
                break;
        }
    }

    /**
     * 处理Hive配置变更
     * 
     * @param event 配置变更事件
     */
    private void handleHiveConfigChange(ConfigChangeEvent event) {
        String configKey = event.getKey();
        
        switch (configKey) {
            case "hive.batch.size":
                // 更新Hive写入批处理大小
                try {
                    int batchSize = Integer.parseInt(event.getNewValue().toString());
                    hiveWriter.updateBatchSize(batchSize);
                    logger.info("已更新Hive写入批处理大小: {}", batchSize);
                } catch (NumberFormatException e) {
                    logger.warn("无效的batch.size值: {}", event.getNewValue());
                }
                break;
                
            case "hive.batch.timeout":
                // 更新Hive写入超时时间
                try {
                    int timeout = Integer.parseInt(event.getNewValue().toString());
                    hiveWriter.updateBatchTimeout(timeout);
                    logger.info("已更新Hive写入超时时间: {}", timeout);
                } catch (NumberFormatException e) {
                    logger.warn("无效的batch.timeout值: {}", event.getNewValue());
                }
                break;
                
            case "hive.jdbc.url":
            case "hive.jdbc.username":
            case "hive.jdbc.password":
                // 数据库连接信息变更需要重新初始化连接
                logger.warn("Hive数据库连接信息已变更，需要重新初始化连接: {}", configKey);
                alertManager.sendConfigChangeAlert("Hive配置变更", 
                    "数据库连接信息已变更，需要重新初始化连接: " + configKey);
                break;
                
            default:
                logger.info("Hive配置变更: {} = {}", configKey, event.getNewValue());
                break;
        }
    }

    /**
     * 处理Groovy配置变更
     * 
     * @param event 配置变更事件
     */
    private void handleGroovyConfigChange(ConfigChangeEvent event) {
        String configKey = event.getKey();
        
        switch (configKey) {
            case "groovy.script.path":
                // 脚本路径变更需要重新加载脚本
                logger.info("Groovy脚本路径已变更，重新加载脚本: {}", event.getNewValue());
                groovyScriptEngine.reloadScripts();
                break;
                
            case "groovy.script.cache.enabled":
                // 脚本缓存开关变更
                boolean cacheEnabled = Boolean.parseBoolean(event.getNewValue().toString());
                groovyScriptEngine.setCacheEnabled(cacheEnabled);
                logger.info("已更新Groovy脚本缓存状态: {}", cacheEnabled);
                break;
                
            case "groovy.script.cache.size":
                // 脚本缓存大小变更
                try {
                    int cacheSize = Integer.parseInt(event.getNewValue().toString());
                    groovyScriptEngine.updateCacheSize(cacheSize);
                    logger.info("已更新Groovy脚本缓存大小: {}", cacheSize);
                } catch (NumberFormatException e) {
                    logger.warn("无效的cache.size值: {}", event.getNewValue());
                }
                break;
                
            default:
                logger.info("Groovy配置变更: {} = {}", configKey, event.getNewValue());
                break;
        }
    }

    /**
     * 处理告警配置变更
     * 
     * @param event 配置变更事件
     */
    private void handleAlertConfigChange(ConfigChangeEvent event) {
        String configKey = event.getKey();
        
        switch (configKey) {
            case "alert.mail.enabled":
                // 邮件告警开关变更
                boolean mailEnabled = Boolean.parseBoolean(event.getNewValue().toString());
                alertManager.setMailEnabled(mailEnabled);
                logger.info("已更新邮件告警状态: {}", mailEnabled);
                break;
                
            case "alert.mail.smtp.host":
            case "alert.mail.smtp.port":
            case "alert.mail.recipients":
                // 邮件服务器配置变更需要重新初始化邮件服务
                logger.info("邮件服务器配置已变更，重新初始化邮件服务: {}", configKey);
                alertManager.reinitializeMailService();
                break;
                
            default:
                logger.info("告警配置变更: {} = {}", configKey, event.getNewValue());
                break;
        }
    }

    /**
     * 处理通用配置变更
     * 
     * @param event 配置变更事件
     */
    private void handleGenericConfigChange(ConfigChangeEvent event) {
        logger.info("通用配置变更: {} = {} -> {}", 
                   event.getKey(), event.getOldValue(), event.getNewValue());
        
        // 记录配置变更到系统监控
        systemMonitor.recordConfigChange(event.getKey(), event.getNewValue());
    }
}
